<template>
    <div id="login">
        <img src="./login.png" alt="">
        <div class="form">
            <el-form label-width="80px" size="large" ref="loginForm" :model="loginForm">
                <el-form-item
                    label="账号"
                    prop="username"
                    :rules="[{ required: true, message: '账号不能为空'},]"
                >
                    <el-input  v-model="loginForm.username" ></el-input>
                </el-form-item>
                <el-form-item
                    label="密码"
                    prop="password"
                    :rules="[{ required: true, message: '密码不能为空'},]"
                >
                    <el-input type="password" v-model="loginForm.password" ></el-input>
                </el-form-item>
                <el-form-item>
                     <el-button type="primary" :loading="load" class="submit-btn" @click="submitForm('loginForm')">登录</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import {login} from 'api/server.js'
import {mapMutations} from 'vuex'
export default {
  data() {
    return {
        loginForm:{
            username:"",
            password:""
        },
        load:false
    }
  },
  methods:{
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
            if (valid) {
                this.login();
            } else {
                console.log('error submit!!');
                return false;
            }
        });
      },
      login(){
          this.load=true;
          this.$store.dispatch('loginByUsername',this.loginForm).then(()=>{
                this.load=false;
                let redirect = decodeURIComponent(this.$route.query.redirect || '/');
                this.$router.push({
                    path: redirect
                });
          }).catch(()=>{
              this.load=false;
          })
      },
      ...mapMutations(['SET_LOGININFO'])
  }
}
</script>

<style scoped lang="scss">
.form{
    width:400px;
    margin:0 auto;
}
.submit-btn{
    width:100%;
    text-align: center;
}
</style>